package com.wang.friend.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wang.common.security.exception.ServiceException;
import com.wang.friend.domain.question.Question;
import com.wang.friend.mapper.question.QuestionMapper;
import com.wang.common.core.constants.CacheConstants;
import com.wang.common.core.enums.ResultCode;
import com.wang.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class QuestionCacheManager {

    @Autowired
    private RedisService redisService;

    @Autowired
    private QuestionMapper questionMapper;

    /**
     * 获取题目id列表的长度
     * @return 返回长度
     */
    public Long getListSize(){
        return redisService.getListSize(CacheConstants.QUESTION_LIST);
    }

    /**
     * 刷新题目id列表缓存
     */
    public void refreshCache(){
        //从数据库中查询数据
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                .select(Question::getQuestionId).orderByDesc(Question::getCreateTime));
        //校验是否为空
        if (CollectionUtil.isEmpty(questionList)){
            return;
        }
        //转换数据类型
        List<Long> questionIdList = new ArrayList<>();
        for (Question question : questionList){
            questionIdList.add(question.getQuestionId());
        }
        //加入redis中
        redisService.rightPushAll(CacheConstants.QUESTION_LIST,questionIdList);
    }

    /**
     * 找到当前题目的前一个题目的id
     * @param questionId 当前题目的id
     * @return 返回前一个题目id
     */
    public Long preQuestion(Long questionId){
        //获取到当前题目在list中的下标
        Long index = redisService.indexOfForList(CacheConstants.QUESTION_LIST,questionId);
        if (index == 0){
            //如果等于0,说明已经是第一题了
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
        //获取到前一个题目(index-1)在list中的id
        return redisService.indexForList(CacheConstants.QUESTION_LIST,index-1,Long.class);
    }

    /**
     * 找到当前题目的后一个id
     * @param questionId 当前题目的id
     * @return 返回后一个题目的id
     */
    public Long nextQuestion(Long questionId){
        //获取到当前题目在list中的下标
        Long index = redisService.indexOfForList(CacheConstants.QUESTION_LIST,questionId);
        Long lastIndex = getListSize() - 1;
        if (index.equals(lastIndex)){
            //如果等于lastIndex,说明已经是最后题了
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        //获取到后一个题目(index+1)在list中的id
        return redisService.indexForList(CacheConstants.QUESTION_LIST,index+1,Long.class);
    }
}
